<!DOCTYPE html>












  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
























<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/css/main.css?v=7.0.1">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.0.1">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.0.1">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=7.0.1">


  <link rel="mask-icon" href="/images/logo.svg?v=7.0.1" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.0.1',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: true,
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="相信大家在实际工作场景中会遇到这样的情况，系统之间存在数据交换，为了不影响正常服务器运，我们需要在每天的凌晨来进行数据交换，但是让程序每天凌晨自动执行呢，下面带大家来了解一下springboot定时任务调度。">
<meta name="keywords" content="SpringBoot,Scheduled">
<meta property="og:type" content="article">
<meta property="og:title" content="【SpringBoot2.0系列10】SpringBoot之@Scheduled任务调度">
<meta property="og:url" content="http://www.yukonga.cn/2018/08/27/【SpringBoot2-0系列10】SpringBoot之-Scheduled任务调度/index.html">
<meta property="og:site_name" content="yukong&#39;s blog">
<meta property="og:description" content="相信大家在实际工作场景中会遇到这样的情况，系统之间存在数据交换，为了不影响正常服务器运，我们需要在每天的凌晨来进行数据交换，但是让程序每天凌晨自动执行呢，下面带大家来了解一下springboot定时任务调度。">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-060800.jpg">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-060821.jpg">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-060840.jpg">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-055539.jpg">
<meta property="og:updated_time" content="2019-05-07T06:08:47.120Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【SpringBoot2.0系列10】SpringBoot之@Scheduled任务调度">
<meta name="twitter:description" content="相信大家在实际工作场景中会遇到这样的情况，系统之间存在数据交换，为了不影响正常服务器运，我们需要在每天的凌晨来进行数据交换，但是让程序每天凌晨自动执行呢，下面带大家来了解一下springboot定时任务调度。">
<meta name="twitter:image" content="http://cdn.yukonga.cn/2019-05-07-060800.jpg">



  <link rel="alternate" href="/atom.xml" title="yukong's blog" type="application/atom+xml">




  <link rel="canonical" href="http://www.yukonga.cn/2018/08/27/【SpringBoot2-0系列10】SpringBoot之-Scheduled任务调度/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>【SpringBoot2.0系列10】SpringBoot之@Scheduled任务调度 | yukong's blog</title>
  






  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?45b7a3cfe46b3fa2c5d46f59f590664e";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>







  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">yukong's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">learning program</p>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>

      
      
    </ul>
  

  

  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://www.yukonga.cn/2018/08/27/【SpringBoot2-0系列10】SpringBoot之-Scheduled任务调度/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="yukong">
      <meta itemprop="description" content="你若对得起时间，时间便对得起你">
      <meta itemprop="image" content="/uploads/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="yukong's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">【SpringBoot2.0系列10】SpringBoot之@Scheduled任务调度

              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-08-27 20:24:29" itemprop="dateCreated datePublished" datetime="2018-08-27T20:24:29+08:00">2018-08-27</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-05-07 14:08:47" itemprop="dateModified" datetime="2019-05-07T14:08:47+08:00">2019-05-07</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing"><a href="/categories/SpringBoot/" itemprop="url" rel="index"><span itemprop="name">SpringBoot</span></a></span>

                
                
              
            </span>
          

          
            
            
              
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
            
                <span class="post-meta-item-text">评论数：</span>
                <a href="/2018/08/27/【SpringBoot2-0系列10】SpringBoot之-Scheduled任务调度/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2018/08/27/【SpringBoot2-0系列10】SpringBoot之-Scheduled任务调度/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
            <span id="/2018/08/27/【SpringBoot2-0系列10】SpringBoot之-Scheduled任务调度/" class="leancloud_visitors" data-flag-title="【SpringBoot2.0系列10】SpringBoot之@Scheduled任务调度">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              
                <span class="post-meta-item-text">阅读次数：</span>
              
                <span class="leancloud-visitors-count"></span>
            </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>相信大家在实际工作场景中会遇到这样的情况，系统之间存在数据交换，为了不影响正常服务器运，我们需要在每天的凌晨来进行数据交换，但是让程序每天凌晨自动执行呢，下面带大家来了解一下springboot定时任务调度。</p>
<a id="more"></a>
<h1 id="实现"><a class="markdownIt-Anchor" href="#实现"></a> 实现</h1>
<p>其实在springboot中实现定时任务调度十分的，下面我们将实现一个简单的定时任务调度调度。</p>
<h2 id="1-依赖"><a class="markdownIt-Anchor" href="#1-依赖"></a> 1、依赖</h2>
<p><code>scheduled</code> 依赖是<code>spring-context</code>这个jar包其中我们的<code>spring-boot-starter</code>已经依赖spring的一些核心jar，所以我们只需要添加<code>spring-boot-starter</code>即可</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-test<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">scope</span>&gt;</span>test<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h2 id="2-引入enablescheduling"><a class="markdownIt-Anchor" href="#2-引入enablescheduling"></a> 2、引入<code>@EnableScheduling</code></h2>
<p>我们需要在Spring Boot的主类中加入@EnableScheduling注解，开启定时任务的配置</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> yukong</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@data</span> 2018年8月27日19:00:21</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@EnableScheduling</span></span><br><span class="line"><span class="meta">@SpringBootApplication</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Chapter9Application</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        SpringApplication.run(Chapter9Application.class, args);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="3-实现定时任务"><a class="markdownIt-Anchor" href="#3-实现定时任务"></a> 3、实现定时任务</h2>
<p>我们创建一个名为<code>ScheduledTask</code>的任务类</p>
<h3 id="311-scheduledfixeddelay-5000"><a class="markdownIt-Anchor" href="#311-scheduledfixeddelay-5000"></a> 3.1.1 @Scheduled(fixedDelay= 5000)</h3>
<p>@Scheduled(fixedDelay= 5000) 指的是上一次开始执行时间点之后5秒再执行。可能大家不知道什么意思那么下面代码编写，运行一下就知道了。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> yukong</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2018/8/27</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@description</span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ScheduledTask</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    Logger logger = LoggerFactory.getLogger(ScheduledTask.class);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> SimpleDateFormat simpleDateFormat = <span class="keyword">new</span> SimpleDateFormat(<span class="string">"yyyy-MM-dd HH:mm:ss"</span>);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 从当前方法开始执行后5s再次执行</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Scheduled</span>(fixedDelay= <span class="number">5000</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">scheduledTask2</span><span class="params">()</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">        logger.info(<span class="string">"当前时间为：&#123;&#125;"</span>, simpleDateFormat.format(<span class="keyword">new</span> Date()));</span><br><span class="line">        Thread.sleep(<span class="number">3000L</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面需要注意的是我们通过<code>@Scheduled</code>注解表示这个一个定时调度的任务，具体的调度策略是根据注解中的属性决定，在当前代码中fixedDelay= 5000代表从当前方法开始执行<strong>完成</strong>后5s再次执行,注意加粗部分。另外需要注意的我们的类需要用<code>@Component</code>注解标识，不然spring是无法感知这些定时任务的。</p>
<h3 id="312测试-结论"><a class="markdownIt-Anchor" href="#312测试-结论"></a> 3.1.2测试、结论</h3>
<p>运行结果如下<br>
<img src="http://cdn.yukonga.cn/2019-05-07-060800.jpg" alt=""></p>
<p>图中是每隔8s执行一次，但是我们明明设置的5s的间隔，这是怎么回事呢。回头看看我刚刚说的<code>fixedDelay = 5000</code>的特点：代表从当前方法开始执行<strong>完成</strong>后5s再次执行。在看看定时调用的方法中<code>Thread.sleep(3000)</code>就瞬间明白了。原来<code>fixedDelay</code> = 代表从当前方法开始执行<strong>完成</strong>后间隔一定时间再次执行。那么不需要等待当前方法执行完成又是怎么写的呢？</p>
<h3 id="321-scheduledfixedrate-5000"><a class="markdownIt-Anchor" href="#321-scheduledfixedrate-5000"></a> 3.2.1 @Scheduled(fixedRate= 5000)</h3>
<p>其实很简单的，我们只需要将<code>fixedDelay = 5000</code>改成<code>fixedRate = 5000</code>即可。<br>
<code>fixedRate = 5000</code>代表 从当前方<strong>开始执后</strong>5s再次执行，代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 从当前方法开始执行后5s再次执行</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Scheduled</span>(fixedRate = <span class="number">5000</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">scheduledTask1</span><span class="params">()</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">    logger.info(<span class="string">"当前时间为：&#123;&#125;"</span>, simpleDateFormat.format(<span class="keyword">new</span> Date()));</span><br><span class="line">    Thread.sleep(<span class="number">3000L</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="322测试-结论"><a class="markdownIt-Anchor" href="#322测试-结论"></a> 3.2.2测试、结论</h3>
<p>执行结果如图，如预期的一样每隔5s秒执行一次。<br>
<img src="http://cdn.yukonga.cn/2019-05-07-060821.jpg" alt=""></p>
<h3 id="331-scheduledcron-0515"><a class="markdownIt-Anchor" href="#331-scheduledcron-0515"></a> 3.3.1      @Scheduled(cron = “0,5,15 * * * * ?”)</h3>
<p>如果你还需要更复杂的定时任务策略，那么你就可能需要用到<code>cron</code>表达式。<br>
1.cron表达式格式：<br>
{秒数} {分钟} {小时} {日期} {月份} {星期} {年份(可为空)}<br>
2.cron表达式各占位符解释：<br>
{秒数} ==&gt; 允许值范围: 0~59 ,不允许为空值，若值不合法，调度器将抛出SchedulerException异常<br>
“*” 代表每隔1秒钟触发；<br>
“,” 代表在指定的秒数触发，比如&quot;0,15,45&quot;代表0秒、15秒和45秒时触发任务<br>
&quot;-&quot;代表在指定的范围内触发，比如&quot;25-45&quot;代表从25秒开始触发到45秒结束触发，每隔1秒触发1次<br>
“/“代表触发步进(step)，”/“前面的值代表初始值(”*“等同&quot;0”)，后面的值代表偏移量，比如&quot;0/20&quot;或者”*/20&quot;代表从0秒钟开始，每隔20秒钟触发1次，即0秒触发1次，20秒触发1次，40秒触发1次；&quot;5/20&quot;代表5秒触发1次，25秒触发1次，45秒触发1次；&quot;10-45/20&quot;代表在[10,45]内步进20秒命中的时间点触发，即10秒触发1次，30秒触发1次<br>
{分钟} ==&gt; 允许值范围: 0~59 ,不允许为空值，若值不合法，调度器将抛出SchedulerException异常<br>
“*” 代表每隔1分钟触发；<br>
&quot;,&quot;代表在指定的分钟触发，比如&quot;10,20,40&quot;代表10分钟、20分钟和40分钟时触发任务<br>
“-” 代表在指定的范围内触发，比如&quot;5-30&quot;代表从5分钟开始触发到30分钟结束触 发，每隔1分钟触发<br>
“/“代表触发步进(step)，”/“前面的值代表初始值(”*“等同&quot;0”)，后面的值代表偏移量，比如&quot;0/25&quot;或者”*/25&quot;代表从0分钟开始，每隔25分钟触发1次，即0分钟触发1次，第25分钟触发1次，第50分钟触发1次；&quot;5/25&quot;代表5分钟触发1次，30分钟触发1次，55分钟触发1次；&quot;10-45/20&quot;代表在[10,45]内步进20分钟命中的时间点触发，即10分钟触发1次，30分钟触发1次<br>
{小时} ==&gt; 允许值范围: 0~23 ,不允许为空值，若值不合法，调度器将抛出SchedulerException异常<br>
“*” 代表每隔1小时触发；<br>
&quot;,&quot;代表在指定的时间点触发，比如&quot;10,20,23&quot;代表10点钟、20点钟和23点触发任务<br>
&quot;-&quot;代表在指定的时间段内触发，比如&quot;20-23&quot;代表从20点开始触发到23点结束触发，每隔1小时触发<br>
“/“代表触发步进(step)，”/“前面的值代表初始值(”*“等同&quot;0”)，后面的值代表偏移量，比如&quot;0/1&quot;或者”*/1&quot;代表从0点开始触发，每隔1小时触发1次；&quot;1/2&quot;代表从1点开始触发，以后每隔2小时触发一次；&quot;19-20/2&quot;表达式将只在19点触发<br>
{日期} ==&gt; 允许值范围: 1~31 ,不允许为空值，若值不合法，调度器将抛出SchedulerException异常<br>
“*” 代表每天触发；<br>
&quot;?&quot;与{星期}互斥，即意味着若明确指定{星期}触发，则表示{日期}无意义，以免引起 冲突和混乱<br>
“,” 代表在指定的日期触发，比如&quot;1,10,20&quot;代表1号、10号和20号这3天触发<br>
&quot;-&quot;代表在指定的日期范围内触发，比如&quot;10-15&quot;代表从10号开始触发到15号结束触发，每隔1天触发<br>
“/“代表触发步进(step)，”/“前面的值代表初始值(”*“等同&quot;1”)，后面的值代表偏移量，比如&quot;1/5&quot;或者”*/5&quot;代表从1号开始触发，每隔5天触发1次；&quot;10/5&quot;代表从10号开始触发，以后每隔5天触发一次；“1-10/2&quot;表达式意味着在[1,10]范围内，每隔2天触发，即1号，3号，5号，7号，9号触发<br>
“L” 如果{日期}占位符如果是&quot;L”，即意味着当月的最后一天触发<br>
&quot;W &quot;意味着在本月内离当天最近的工作日触发，所谓最近工作日，即当天到工作日的前后最短距离，如果当天即为工作日，则距离为0；所谓本月内的说法，就是不能跨月取到最近工作日，即使前/后月份的最后一天/第一天确实满足最近工作日；因此，&quot;LW&quot;则意味着本月的最后一个工作日触发，&quot;W&quot;强烈依赖{月份}<br>
“C” 根据日历触发，由于使用较少，暂时不做解释<br>
{月份} ==&gt; 允许值范围: 1~12 (JAN-DEC),不允许为空值，若值不合法，调度器将抛出SchedulerException异常<br>
“*” 代表每个月都触发；<br>
“,” 代表在指定的月份触发，比如&quot;1,6,12&quot;代表1月份、6月份和12月份触发任务<br>
&quot;-&quot;代表在指定的月份范围内触发，比如&quot;1-6&quot;代表从1月份开始触发到6月份结束触发，每隔1个月触发<br>
“/“代表触发步进(step)，”/“前面的值代表初始值(”*“等同&quot;1”)，后面的值代表偏移量，比如&quot;1/2&quot;或者”*/2&quot;代表从1月份开始触发，每隔2个月触发1次；&quot;6/6&quot;代表从6月份开始触发，以后每隔6个月触发一次；&quot;1-6/12&quot;表达式意味着每年1月份触发<br>
{星期} ==&gt; 允许值范围: 1~7 (SUN-SAT),1代表星期天(一星期的第一天)，以此类推，7代表星期六(一星期的最后一天)，不允许为空值，若值不合法，调度器将抛出SchedulerException异常<br>
“*” 代表每星期都触发；<br>
&quot;?&quot;与{日期}互斥，即意味着若明确指定{日期}触发，则表示{星期}无意义，以免引起冲突和混乱<br>
“,” 代表在指定的星期约定触发，比如&quot;1,3,5&quot;代表星期天、星期二和星期四触发<br>
&quot;-&quot;代表在指定的星期范围内触发，比如&quot;2-4&quot;代表从星期一开始触发到星期三结束触发，每隔1天触发<br>
“/“代表触发步进(step)，”/“前面的值代表初始值(”*“等同&quot;1”)，后面的值代表偏移量，比如&quot;1/3&quot;或者”*/3&quot;代表从星期天开始触发，每隔3天触发1次；&quot;1-5/2&quot;表达式意味着在[1,5]范围内，每隔2天触发，即星期天、星期二、星期四触发<br>
“L&quot;如果{星期}占位符如果是&quot;L”，即意味着星期的的最后一天触发，即星期六触发，L= 7或者 L = SAT，因此，&quot;5L&quot;意味着一个月的最后一个星期四触发<br>
&quot;#“用来指定具体的周数，”#“前面代表星期，”#&quot;后面代表本月第几周，比如&quot;2#2&quot;表示本月第二周的星期一，&quot;5#3&quot;表示本月第三周的星期四，因此，“5L&quot;这种形式只不过是”#&quot;的特殊形式而已<br>
“C” 根据日历触发，由于使用较少，暂时不做解释<br>
{年份} ==&gt; 允许值范围: 1970~2099 ,允许为空，若值不合法，调度器将抛出SchedulerException异常<br>
&quot;*&quot;代表每年都触发；<br>
&quot;,&quot;代表在指定的年份才触发，比如&quot;2011,2012,2013&quot;代表2011年、2012年和2013年触发任务<br>
&quot;-“代表在指定的年份范围内触发，比如&quot;2011-2020&quot;代表从2011年开始触发到2020年结束触发，每隔1年触发<br>
“/“代表触发步进(step)，”/“前面的值代表初始值(”*“等同&quot;1970”)，后面的值代表偏移量，比如&quot;2011/2&quot;或者”*/2&quot;代表从2011年开始触发，每隔2年触发1次<br>
注意：除了{日期}和{星期}可以使用”?&quot;来实现互斥，表达无意义的信息之外，其他占位符都要具有具体的时间含义，且依赖关系为：年-&gt;月-&gt;日期(星期)-&gt;小时-&gt;分钟-&gt;秒数<br>
具体cron你可以参考<a href="https://blog.csdn.net/li295214001/article/details/52065634" target="_blank" rel="noopener">cron详解</a></p>
<p>现在我们实现一个每分钟的第0,5,15秒执行一次，那么对应的cron表达式应为<code>0,5,15 * * * * ?</code><br>
实现的代码如下</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Scheduled</span>(cron = <span class="string">"0,5,15 * * * * ?"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">cronTask</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        logger.info(<span class="string">"当前时间为：&#123;&#125;"</span>, simpleDateFormat.format(<span class="keyword">new</span> Date()));</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<h3 id="332运行"><a class="markdownIt-Anchor" href="#332运行"></a> 3.3.2运行</h3>
<p>启动，运行结果如下：<br>
<img src="http://cdn.yukonga.cn/2019-05-07-060840.jpg" alt=""><br>
每分钟的第0,5,15秒都执行，如果你还需要其他的规则，只需要更改对应cron表达式，相信cron的强大能够满足所有的业务场景。</p>
<h1 id="结语"><a class="markdownIt-Anchor" href="#结语"></a> 结语</h1>
<p>相信通过本次学习，大家应该知道如何在springboot使用定时任务了。<br>
最后配套教程的代码全部在这里<br>
<a href="https://github.com/YuKongEr/SpringBoot-Study" target="_blank" rel="noopener">github https://github.com/YuKongEr/SpringBoot-Study</a>。麻烦点个star或者fork吧。</p>
<p>最后欢迎大家关注一下我的个人公众号。一起交流一起学习，有问必答。<br>
<img src="http://cdn.yukonga.cn/2019-05-07-055539.jpg" alt=""></p>

      
    </div>

    

    
    
    

    

    
      
    
    
      <div>
        <div id="reward-container">
  <div>喜欢就请博主喝个☕️吧</div>
  <button id="reward-button" disable="enable" onclick="var qr = document.getElementById(&quot;qr&quot;); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">

    
      
      
        
      
      <div style="display: inline-block">
        <img src="/images/wechatpay.jpg" alt="yukong 微信支付">
        <p>微信支付</p>
      </div>
    
      
      
        
      
      <div style="display: inline-block">
        <img src="/images/alipay.jpg" alt="yukong 支付宝">
        <p>支付宝</p>
      </div>
    

  </div>
</div>

      </div>
    

    
      <div>
        




  



<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>yukong</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    
    <a href="http://www.yukonga.cn/2018/08/27/【SpringBoot2-0系列10】SpringBoot之-Scheduled任务调度/" title="【SpringBoot2.0系列10】SpringBoot之@Scheduled任务调度">http://www.yukonga.cn/2018/08/27/【SpringBoot2-0系列10】SpringBoot之-Scheduled任务调度/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc/4.0/" rel="noopener" target="_blank"><i class="fa fa-fw fa-creative-commons"></i>BY-NC</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    
    

      <div>
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/SpringBoot/" rel="tag"><i class="fa fa-tag"></i> SpringBoot</a>
          
            <a href="/tags/Scheduled/" rel="tag"><i class="fa fa-tag"></i> Scheduled</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/08/25/解开BIO、NIO、AIO神秘的面纱/" rel="next" title="解开BIO、NIO、AIO神秘的面纱">
                <i class="fa fa-chevron-left"></i> 解开BIO、NIO、AIO神秘的面纱
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/08/29/【java并发编程实战1】何为线程安全性/" rel="prev" title="【java并发编程实战1】何为线程安全性">
                【java并发编程实战1】何为线程安全性 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div class="comments" id="comments">
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/uploads/avatar.png" alt="yukong">
            
              <p class="site-author-name" itemprop="name">yukong</p>
              <div class="site-description motion-element" itemprop="description">你若对得起时间，时间便对得起你</div>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">26</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  
                    
                      <a href="/categories/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">6</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  
                    
                      <a href="/tags/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">36</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://github.com/YuKongEr" title="GitHub &rarr; https://github.com/YuKongEr" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="mailto:yukongcode@gmail.com" title="E-Mail &rarr; mailto:yukongcode@gmail.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://www.jianshu.com/u/bc2e35b66293" title="简书 &rarr; https://www.jianshu.com/u/bc2e35b66293" rel="noopener" target="_blank"><i class="fa fa-fw fa-skype"></i>简书</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://blog.csdn.net/xp541130126" title="csdn &rarr; https://blog.csdn.net/xp541130126" rel="noopener" target="_blank"><i class="fa fa-fw fa-vk"></i>csdn</a>
                </span>
              
            </div>
          

          

          
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#实现"><span class="nav-number">1.</span> <span class="nav-text"> 实现</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-依赖"><span class="nav-number">1.1.</span> <span class="nav-text"> 1、依赖</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-引入enablescheduling"><span class="nav-number">1.2.</span> <span class="nav-text"> 2、引入@EnableScheduling</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-实现定时任务"><span class="nav-number">1.3.</span> <span class="nav-text"> 3、实现定时任务</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#311-scheduledfixeddelay-5000"><span class="nav-number">1.3.1.</span> <span class="nav-text"> 3.1.1 @Scheduled(fixedDelay= 5000)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#312测试-结论"><span class="nav-number">1.3.2.</span> <span class="nav-text"> 3.1.2测试、结论</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#321-scheduledfixedrate-5000"><span class="nav-number">1.3.3.</span> <span class="nav-text"> 3.2.1 @Scheduled(fixedRate= 5000)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#322测试-结论"><span class="nav-number">1.3.4.</span> <span class="nav-text"> 3.2.2测试、结论</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#331-scheduledcron-0515"><span class="nav-number">1.3.5.</span> <span class="nav-text"> 3.3.1      @Scheduled(cron = “0,5,15 * * * * ?”)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#332运行"><span class="nav-number">1.3.6.</span> <span class="nav-text"> 3.3.2运行</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#结语"><span class="nav-number">2.</span> <span class="nav-text"> 结语</span></a></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">yukong</span>

  

  
</div>
<div class="BbeiAn-info">
浙ICP备 -
<a target="_blank" href="http://www.miitbeian.gov.cn">19015067号</a>

</div>









        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="post-meta-item-icon">
      <i class="fa fa-user"></i>
      您是访问本站的第&nbsp
    </span>
    <span class="site-uv" title="总访客量">
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      &nbsp 位朋友
    </span>
  

  
    <span class="post-meta-divider">|</span>
  

  
    <span class="post-meta-item-icon">
      <i class="fa fa-eye"></i>
      本站总共访问&nbsp
    </span>
    <span class="site-pv" title="总访问量">
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>









        
      </div>
    </footer>

    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  <script src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>


  


  <script src="/js/src/utils.js?v=7.0.1"></script>

  <script src="/js/src/motion.js?v=7.0.1"></script>



  
  


  <script src="/js/src/affix.js?v=7.0.1"></script>

  <script src="/js/src/schemes/pisces.js?v=7.0.1"></script>




  
  <script src="/js/src/scrollspy.js?v=7.0.1"></script>
<script src="/js/src/post-details.js?v=7.0.1"></script>



  


  <script src="/js/src/next-boot.js?v=7.0.1"></script>


  

  

  

  
  

<script src="//cdn1.lncld.net/static/js/3.11.1/av-min.js"></script>



<script src="//unpkg.com/valine/dist/Valine.min.js"></script>

<script>
  var GUEST = ['nick', 'mail', 'link'];
  var guest = 'nick,mail,link';
  guest = guest.split(',').filter(function(item) {
    return GUEST.indexOf(item) > -1;
  });
  new Valine({
    el: '#comments',
    verify: false,
    notify: false,
    appId: 'UXuVTqzKQgCJRWTkO8K60EXL-gzGzoHsz',
    appKey: 'n3ohmj1CGAM1GUfp6SqF4LXh',
    placeholder: 'Just go go',
    avatar: 'mm',
    meta: guest,
    pageSize: '10' || 10,
    visitor: false,
    lang: 'zh-cn' || 'zh-cn'
  });
</script>




  


  




  
  
  <script>
    
    function addCount(Counter) {
      var $visitors = $('.leancloud_visitors');
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();

      Counter('get', '/classes/Counter', { where: JSON.stringify({ url }) })
        .done(function({ results }) {
          if (results.length > 0) {
            var counter = results[0];
            
            Counter('put', '/classes/Counter/' + counter.objectId, JSON.stringify({ time: { '__op': 'Increment', 'amount': 1 } }))
            
              .done(function() {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.time + 1);
              })
            
              .fail(function ({ responseJSON }) {
                console.log('Failed to save Visitor num, with error message: ' + responseJSON.error);
              })
          } else {
            
              Counter('post', '/classes/Counter', JSON.stringify({ title: title, url: url, time: 1 }))
                .done(function() {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(1);
                })
                .fail(function() {
                  console.log('Failed to create');
                });
            
          }
        })
        .fail(function ({ responseJSON }) {
          console.log('LeanCloud Counter Error: ' + responseJSON.code + ' ' + responseJSON.error);
        });
    }
    

    $(function() {
      $.get('https://app-router.leancloud.cn/2/route?appId=' + 'UXuVTqzKQgCJRWTkO8K60EXL-gzGzoHsz')
        .done(function({ api_server }) {
          var Counter = function(method, url, data) {
            return $.ajax({
              method: method,
              url: 'https://' + api_server + '/1.1' + url,
              headers: {
                'X-LC-Id': 'UXuVTqzKQgCJRWTkO8K60EXL-gzGzoHsz',
                'X-LC-Key': 'n3ohmj1CGAM1GUfp6SqF4LXh',
                'Content-Type': 'application/json',
              },
              data: data
            });
          };
          
            addCount(Counter);
          
        });
    });
  </script>



  

  

  

  

  

  

  

  

  

  

  
<script>
  $('.highlight').each(function(i, e) {
    var $wrap = $('<div>').addClass('highlight-wrap');
    $(e).after($wrap);
    $wrap.append($('<button>').addClass('copy-btn').append('复制').on('click', function(e) {
      var code = $(this).parent().find('.code').find('.line').map(function(i, e) {
        return $(e).text();
      }).toArray().join('\n');
      var ta = document.createElement('textarea');
      var yPosition = window.pageYOffset || document.documentElement.scrollTop;
      ta.style.top = yPosition + 'px'; // Prevent page scroll
      ta.style.position = 'absolute';
      ta.style.opacity = '0';
      ta.readOnly = true;
      ta.value = code;
      document.body.appendChild(ta);
      ta.select();
      ta.setSelectionRange(0, code.length);
      ta.readOnly = false;
      var result = document.execCommand('copy');
      
        if (result) $(this).text('复制成功');
        else $(this).text('复制失败');
      
      ta.blur(); // For iOS
      $(this).blur();
    })).on('mouseleave', function(e) {
      var $b = $(this).find('.copy-btn');
      setTimeout(function() {
        $b.text('复制');
      }, 300);
    }).append(e);
  })
</script>


  

  

</body>
</html>
